package com.fy.exam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fy.core.consts.ExamContant;
import com.fy.core.context.AuthContext;
import com.fy.core.dto.PageDto;
import com.fy.core.vo.ApiRest;
import com.fy.core.vo.PageResult;
import com.fy.exam.dto.ExamCreateDto;
import com.fy.exam.entity.Exam;
import com.fy.exam.entity.ExamDepart;
import com.fy.exam.entity.ExamUser;
import com.fy.exam.mapper.ExamDepartMapper;
import com.fy.exam.mapper.ExamMapper;
import com.fy.exam.mapper.ExamRepoMapper;
import com.fy.exam.mapper.ExamUserMapper;
import com.fy.exam.service.ExamService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author hxd
 * @since 2023-06-19
 */
@Service
@Slf4j
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam> implements ExamService {
    @Autowired
    private ExamRepoMapper examRepoMapper;
    @Autowired
    private ExamDepartMapper examDepartMapper;
    @Autowired
    private ExamUserMapper examUserMapper;
    @Override
    public PageResult<Exam> pageFind(PageDto<Exam> pageDto) {
        IPage<Exam> page=new Page<>(pageDto.getNow(),pageDto.getSize());
        Exam where=pageDto.getWhere();
        QueryWrapper<Exam> examQueryWrapper=new QueryWrapper<>();
        if (!StringUtils.isEmpty(where.getTitle())){
            examQueryWrapper.lambda().like(Exam::getTitle,where.getTitle());
        }
        if (!StringUtils.isEmpty(where.getOpenType())){
            examQueryWrapper.lambda().eq(Exam::getOpenType,where.getOpenType());
        }
        if (!StringUtils.isEmpty(where.getStartTime())){
            examQueryWrapper.lambda().eq(Exam::getStartTime,where.getStartTime());
        }
        if (!StringUtils.isEmpty(where.getEndTime())){
            examQueryWrapper.lambda().eq(Exam::getEndTime,where.getEndTime());
        }
        IPage<Exam> pageInfo = this.baseMapper.selectPage(page, examQueryWrapper);
        PageResult<Exam> pageResult=new PageResult<>();
        pageResult.setPages(pageInfo.getPages());
        pageResult.setList(pageInfo.getRecords());
        pageResult.setTotal(pageInfo.getTotal());
        return pageResult;
    }

    @Override
    public ApiRest save(ExamCreateDto examCreateDto) {
        //参数校验

        //保存exam
        Exam exam=new Exam();
        BeanUtil.copyProperties(examCreateDto,exam,true);
        if (examCreateDto.getId()==null){
            exam.setId(IdWorker.getIdStr());
            exam.setCreateTime(new Date());
        }else {
            exam.setId(examCreateDto.getId());
        }
        exam.setUpdateTime(new Date());
        exam.setJoinType(ExamContant.ZUJUAN_REPO);
        exam.setLevel(ExamContant.LEVEL_PUTONG);
        exam.setState(ExamContant.CREATE);
        this.baseMapper.insert(exam);
        //保存exam_repo
        examCreateDto.getExamRepos().forEach(examRepo -> {
            examRepo.setId(IdWorker.getIdStr());
            examRepo.setExamId(exam.getId());
            examRepoMapper.insert(examRepo);
        });
        //保存exam_departIds
        if (examCreateDto.getOpenType()==ExamContant.OPENT_DEPART){
            examCreateDto.getDepartIds().forEach(departId->{
                ExamDepart examDepart=new ExamDepart();
                examDepart.setDepartId(departId);
                examDepart.setId(IdWorker.getIdStr());
                examDepart.setExamId(exam.getId());
                examDepartMapper.insert(examDepart);
            });
        }
        //保存exam_user
        if (examCreateDto.getOpenType()==ExamContant.OPENT_SPECIFY){
            examCreateDto.getUserIds().forEach(userId->{
                ExamUser examUser=new ExamUser();
                examUser.setExamId(exam.getId());
                examUser.setUserId(userId);
                examUser.setId(IdWorker.getIdStr());
                examUserMapper.insert(examUser);
            });
        }
        log.info("{}创建了{}考试", new Date(), examCreateDto.getTitle());
        return ApiRest.success("创建考试成功","");
    }

    @Override
    public ApiRest<List<Exam>> selectMyExams() {
        //获取用户id
        Long userId = AuthContext.getUser().getUserId();
        List<Exam> examList = this.baseMapper.findMyExam(userId + "");

        return ApiRest.success(examList);
    }
}
